package cn.com.ddapp.ddm.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.bumptech.glide.Glide;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.util.LoadingDialog;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TDevice;
import cn.com.ddapp.ddm.util.ToastUtil;
import cn.com.ddapp.ddm.util.photopicker.ImageCaptureManager;
import cn.com.ddapp.ddm.util.photopicker.PhotoPickerActivity;
import cn.com.ddapp.ddm.util.photopicker.PhotoPreviewActivity;
import cn.com.ddapp.ddm.util.photopicker.SelectModel;
import cn.com.ddapp.ddm.util.photopicker.intent.PhotoPickerIntent;
import cn.com.ddapp.ddm.util.photopicker.intent.PhotoPreviewIntent;

/**
 * Created by caopenghui on 2016-08-14.
 */
public class ToShareActivity extends Activity implements  View.OnClickListener, AMapLocationListener {

    @BindView(R.id.toshare_text)
    EditText toshare_text;
    @BindView(R.id.gridView)
    GridView gridView;
    @BindView(R.id.getadd_tv)
    TextView getadd_tv;
    @BindView(R.id.getadd_img)
    CheckBox getadd_img;//是否获取当前位置
    @BindView(R.id.send_share)
    TextView send_share;//发布分享
    private String address;
    String path;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private String depp;
    private static final int REQUEST_CAMERA_CODE = 10;
    private static final int REQUEST_PREVIEW_CODE = 20;
    private ArrayList<String> imagePaths = new ArrayList<>();
    private ImageCaptureManager captureManager; // 相机拍照处理类
    private GridAdapter gridAdapter;
    private List<File> fileList=new ArrayList<File>();
    private Map<String, File> files=new HashMap<>();
    Unbinder unbinder;
    private Handler handler;
    private Handler draftHandler;
    private String userId;
  public static void startIntent(Context context){
      Intent intent=new Intent(context,ToShareActivity.class);
      context.startActivity(intent);
  }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(TDevice.isTablet(getApplicationContext())){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 横屏
        }else{
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        }
        setContentView(R.layout.activity_toshare);
        unbinder= ButterKnife.bind(this);
        initView();
        userId= SPUtils.getStringData(getApplicationContext(),SPUtils.USERID);
        location();
    }


    public void initView() {
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gridView.setNumColumns(cols);

        // preview
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String imgs = (String) parent.getItemAtPosition(position);
                if ("000000".equals(imgs) ){
                    PhotoPickerIntent intent = new PhotoPickerIntent(ToShareActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(6); // 最多选择照片数量，默认为6
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                }else{
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(ToShareActivity.this);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePaths);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }
            }
        });
        imagePaths.add("000000");
        gridAdapter = new GridAdapter(imagePaths);
        gridView.setAdapter(gridAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    Log.i("yu", "list: " + "list = [" + list.size());
                    loadAdpater(list);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    ArrayList<String> ListExtra = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
                    Log.i("yu", "ListExtra: " + "ListExtra = [" + ListExtra.size());
                    loadAdpater(ListExtra);
                    break;
            }
        }
    }

    private void loadAdpater(ArrayList<String> paths){
        if (imagePaths!=null&& imagePaths.size()>0){
            imagePaths.clear();
        }
        if (paths.contains("000000")){
            paths.remove("000000");
        }
        paths.add("000000");
        imagePaths.addAll(paths);
        gridAdapter  = new GridAdapter(imagePaths);
        gridView.setAdapter(gridAdapter);
        try{
            JSONArray obj = new JSONArray(imagePaths);
//            Log.e("--", obj.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    @OnClick({R.id.share_back,R.id.share_right_text,R.id.getadd_img,R.id.send_share})
  public void onClick(View view){

        String content= null;
        try {
            content= URLEncoder.encode(toshare_text.getText().toString(), "utf-8");
            Log.i("aaa","--a"+content);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        switch (view.getId()){
          case R.id.share_back:
              if(!TextUtils.isEmpty(content) ||(imagePaths.size()>1)){
            showToDrafit();
        }else{
            finish();
        }
              break;
          case R.id.share_right_text:
              finish();
              break;
          case R.id.getadd_img:
                if(getadd_img.isChecked()==true){
                    mlocationClient.startLocation();
                    System.out.println("定位");
                }else{
                    mlocationClient.stopLocation();
                    getadd_tv.setText("获取当前位置");
                }
              break;
          case R.id.drafit_sure:
            if(imagePaths.size()==1){
                savetvtoDraft(content);
            }else{
                savetoDraft(content);
            }
              diaog.dismiss();
              break;
          case R.id.drafit_cancle:
              diaog.dismiss();
              finish();
              break;
          case R.id.send_share:
              if(TextUtils.isEmpty(content)){
                ToastUtil.show(ToShareActivity.this,"请输入你的想法",1800);
            }else{
                sendCircle(content);

            }
              break;
      }
  }

    private void savetoDraft(String content) {
        if(getadd_img.isChecked()==false){
            address="";
        }
        LoadingDialog.showDialog(ToShareActivity.this,"保存中。。。",true);
        imagePaths.remove("000000");
        int b;
        HashMap<Integer,List<File>> fileMap = new HashMap<>();
        for(b=0;b<imagePaths.size();b++){
            path=imagePaths.get(b);
            fileList.add(new File(path));
            fileMap.put(b,fileList);
        }
        final OkUtilCallback okUtilCallback=new OkUtilCallback() {
            @Override
            public void onMyResponse(String response, int id) {
                LoadingDialog.clossDialog();
                draftrefrase(response);
            }
        };

        HashMap<String,List<File>> files = new HashMap<>();
        for(Integer position : fileMap.keySet()){
            files.put("files",fileMap.get(position));
        }
        OKUtilAPI.postfile(OKUtilAPI.savecircle, "userId="+userId + "&title=" + content+"&address="+address+"&status=0", okUtilCallback,files);
    }



    private void savetvtoDraft(String content) {
        if(getadd_img.isChecked()==false){
            address="";
        }
        LoadingDialog.showDialog(ToShareActivity.this,"保存中。。。",true);
        final OkUtilCallback okUtilCallback=new OkUtilCallback() {
            @Override
            public void onMyResponse(String response, int id) {
                refraseDro(response);
            }
        };
        HashMap<String,List<File>> files = null;
        OKUtilAPI.postfile(OKUtilAPI.savecircle, "userId="+userId + "&title=" + content+"&address="+address+"&status=0", okUtilCallback,files);

//        params.put("userId", userId);
//        params.put("title", content);
//        params.put("address", address);
//        params.put("status", "0");
//        LoadingDialog.showDialog(ToShareActivity.this,"保存中。。。",true);
//
//        new Thread(){
//            @Override
//            public void run() {
//                Message msg= Message.obtain();
//                String result=OKUtilAPI.saveNoImg(params);
//                try {
//
//                    JSONObject object=new JSONObject(result);
//                    msg.obj=object;
//                    draftHandler.sendMessage(msg);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
    }

    private void refraseDro(String response) {
        try {
            JSONObject objcet=new JSONObject(response);
            String result=objcet.getString("result");
            if(result.equals("OK")){
                BaseApplication.showToastShort("保存到草稿箱成功");
                setResult(555);
                finish();
            }else{
                BaseApplication.showToastShort(result);
                setResult(555);
                finish();
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        LoadingDialog.clossDialog();
    }


    private void sendCircle(final String content) {
        if(getadd_img.isChecked()==false){
            address="";
        }
        if(imagePaths.size()==1){
            LoadingDialog.showDialog(ToShareActivity.this,"发布中。。。",true);
            final OkUtilCallback okUtilCallback=new OkUtilCallback() {
                @Override
                public void onMyResponse(String response, int id) {
                    refrase(response);
                }
            };
            HashMap<String,List<File>> files = null;
            OKUtilAPI.postfile(OKUtilAPI.savecircle, "userId="+userId + "&title=" + content+"&address="+address+"&status=1", okUtilCallback,files);
        }else if(imagePaths.size()>1){

            LoadingDialog.showDialog(ToShareActivity.this,"发布中。。。",true);
            imagePaths.remove("000000");
            int b;
            final OkUtilCallback okUtilCallback=new OkUtilCallback() {
                @Override
                public void onMyResponse(String response, int id) {
                    refrase(response);
                }
            };
            HashMap<Integer,List<File>> fileMap = new HashMap<>();
            for(b=0;b<imagePaths.size();b++){
                path=imagePaths.get(b);
                System.out.println("huaG地址=="+path);
                fileList.add(new File(path));
                fileMap.put(b,fileList);
            }
            HashMap<String,List<File>> files = new HashMap<>();
            for(Integer position : fileMap.keySet()){
                files.put("files",fileMap.get(position));
            }
            OKUtilAPI.postfile(OKUtilAPI.savecircle, "userId="+userId + "&title=" + content+"&address="+address+"&status=1", okUtilCallback,files);
        }

    }

    private void refrase(String response) {
        try {
            JSONObject objcet=new JSONObject(response);
            String result=objcet.getString("result");
            if(result.equals("OK")){
                BaseApplication.showToastShort("发布成功");
                setResult(555);
                finish();
            }else{
                BaseApplication.showToastShort(result);
                setResult(555);
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        LoadingDialog.clossDialog();
    }
    private void draftrefrase(String response) {
        try {
            JSONObject objcet=new JSONObject(response);
            String result=objcet.getString("result");
            if(result.equals("OK")){
                BaseApplication.showToastShort("保存至草稿箱成功");
                finish();
            }else{
                BaseApplication.showToastShort(result);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //是否保存到草稿箱
    Dialog diaog;
    private void showToDrafit() {
       diaog=new Dialog(this);
        diaog.setContentView(R.layout.dialog_tosave_drafit);
        Window window=diaog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        WindowManager.LayoutParams lp=diaog.getWindow().getAttributes();
        lp.gravity= Gravity.CENTER;
        diaog.getWindow().setAttributes(lp);
        try{
            Context context = diaog.getContext();
            int divierId = context.getResources().getIdentifier("android:id/titleDivider", null, null);
            View divider = diaog.findViewById(divierId);
            divider.setBackgroundColor(Color.TRANSPARENT);
        }catch(Exception e){
            //去除Holo主题的蓝色线条
            e.printStackTrace();
        }
        diaog.setCanceledOnTouchOutside(false);
        TextView drafit_cancle= (TextView) diaog.findViewById(R.id.drafit_cancle);
        TextView drafit_sure= (TextView) diaog.findViewById(R.id.drafit_sure);
        drafit_cancle.setOnClickListener(this);
        drafit_sure.setOnClickListener(this);
        diaog.show();
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
//                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                  address=amapLocation.getCity()+amapLocation.getDistrict()+amapLocation.getStreet();
                getadd_tv.setText(address);
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                getadd_tv.setText("定位失败");
            }
    }


    private void location() {
        //声明mLocationOption对象
        mlocationClient = new AMapLocationClient(ToShareActivity.this);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }
    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;
        private LayoutInflater inflater;
        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
            if(listUrls.size() == 7){
                listUrls.remove(listUrls.size()-1);
            }
            inflater = LayoutInflater.from(ToShareActivity.this);
        }

        public int getCount(){
            return  listUrls==null?0:listUrls.size();
        }
        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.item_image, parent,false);
                holder.image = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }

            final String path=listUrls.get(position);
            if (path.equals("000000")){
                holder.image.setImageResource(R.mipmap.add);
            }else {
                Glide.with(ToShareActivity.this)
                        .load(path)
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(holder.image);
            }
            return convertView;
        }
        class ViewHolder {
            ImageView image;
        }
    }
}
